package com.isoft.c2team3service2.controller;

import com.isoft.c2team3service2.bean.ResponseData;
import com.isoft.c2team3service2.entity.ArtistPrivatePost;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.service.ArtistPrivatePostService;
import com.isoft.c2team3service2.service.FileService;
import com.isoft.c2team3service2.util.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 艺人私密帖子控制器
 */
@RestController
@RequestMapping("/artist-private-posts")
public class ArtistPrivatePostController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ArtistPrivatePostController.class);

    @Autowired
    private ArtistPrivatePostService privatePostService;

    @Autowired
    private FileService fileService; // 复用已有的文件上传服务

    /**
     * 发送私密帖子给艺人（需登录且关注该艺人）
     */
    @PostMapping("/{artistId}")  // 接口路径是：/artist-private-posts/{艺人ID}
    public ResponseData<Integer> sendPostToArtist(
            @PathVariable Integer artistId,  // 从路径获取艺人ID
            @RequestParam("title") String title,  // 表单参数：标题
            @RequestParam("content") String content,  // 表单参数：内容
            @RequestParam(value = "file", required = false) MultipartFile file){

        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            return resultT(null, "请先登录");
        }

        // 构建帖子对象
        ArtistPrivatePost post = new ArtistPrivatePost();
        post.setArtistId(artistId);
        post.setTitle(title);
        post.setContent(content);
        // 处理图片上传
        if (file != null) {
            post.setPhotoUrl(fileService.upLoadName("privatePost",file));
        }

        // 发送帖子（自动校验关注关系）
        Integer postId = privatePostService.sendPrivatePostToArtist(post, currentUser);
        if (postId != null) {
            return resultT(postId, "发送私密帖子成功");
        } else {
            return resultT(null, "发送失败：请先关注该艺人");
        }
    }

    /**
     * 查询当前用户向艺人发送的私密帖子
     */
    @GetMapping("/user/all")
    public ResponseData<List<ArtistPrivatePost>> getUserPostsToArtist() {
        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            return resultT(null, "请先登录");
        }

        List<ArtistPrivatePost> posts = privatePostService.getUserPostsToArtist(currentUser.getId());
        return resultT(posts, "查询用户发送的私密帖子");
    }

    /**
     * 艺人查询自己收到的所有私密帖子（需验证艺人身份，此处简化为“当前用户ID=艺人ID”）
     */
    @GetMapping("/artist/received")
    public ResponseData<List<ArtistPrivatePost>> getArtistReceivedPosts(HttpServletRequest request) {
        String authHeader = request.getHeader("authorization");
        log.info("接收到的Authorization头：{}", authHeader); // 输出完整的头信息
        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            return resultT(null, "请先登录");
        }

        // 假设艺人的user_id与artist表的id一致（实际项目需关联艺人用户表）
        Integer artistId = currentUser.getId();
        List<ArtistPrivatePost> posts = privatePostService.getArtistReceivedPosts(artistId);
        return resultT(posts, "查询艺人收到的私密帖子");
    }

    /**
     * 根据帖子ID查询详情（校验权限）
     */
    @GetMapping("/{artistId}")
    public ResponseData<List<ArtistPrivatePost>> getPostsByArtistId(@PathVariable Integer artistId) {
        // 1. 校验用户登录（确保 currentUser 非空）
        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            return new ResponseData<>(401, "请先登录", null); // 明确返回401未授权，而非复用resultT
        }

        // 2. 修复权限校验逻辑：用用户关联的 artistId 对比请求的 artistId
        Integer userAssociatedArtistId = currentUser.getArtistId(); // 用户关联的艺人ID（如2）
        boolean isArtistOwner = userAssociatedArtistId != null && userAssociatedArtistId.equals(artistId); // 艺人本人
        // 假设管理员的userType为2，普通用户为0，艺人用户为1
        boolean isAdmin = currentUser.getUserType() != null && currentUser.getUserType() == 2; // 管理员

        if (!isArtistOwner && !isAdmin) {
            return new ResponseData<>(403, "无权限查看该艺人的私密帖子", null); // 明确返回403禁止访问
        }

        // 3. 查询艺人私密帖子（确保Service层实现正确）
        List<ArtistPrivatePost> posts = privatePostService.getPostsByArtistId(artistId);
        return resultT(posts, "查询艺人私密帖子");
    }
}